#include "StdAfx.h"
#include "MIDI.h"

CMIDI::CMIDI(int beat_clk)
{
   tracks.SetClksPerBeat( beat_clk);//24 );
}

CMIDI::~CMIDI(void)
{
}
void CMIDI::SaveMIDI(char *filename,int track,int division)
{
	jdkmidi::MIDIFileWriteStreamFileName out_stream( filename);

    if( out_stream.IsValid() )
    {
      // the object which takes the midi tracks and writes the midifile to the output stream
      jdkmidi::MIDIFileWriteMultiTrack writer(
        &tracks,
        &out_stream
        );

      // write the output file
      if( writer.Write( track, division ) )
      {
        //Sint return_code = 0;
      }
      else
      {
        fprintf( stderr, "Error writing file '%s'\n", filename );
      }
     }
}
void CMIDI::SetMIDIEvent(int time,int channel,int note,int velocity)
{
	jdkmidi::MIDITimedBigMessage m;
    m.SetTime(time);
    m.SetNoteOn( channel, note, velocity );

    if( !tracks.GetTrack(1)->PutEvent( m ) ) { abort(); }

    m.SetTime(time*2);
    m.SetNoteOff( channel, note, 0 );

    if( !tracks.GetTrack(1)->PutEvent( m ) ) { abort(); } // add messages in time order!
}
void CMIDI::SetTrackData(void)
{
    jdkmidi::MIDITimedBigMessage m;
    m.SetTime( 0 );
    m.SetTimeSig( 4, 4 );  

    if( !tracks.GetTrack(0)->PutEvent(m) ) { abort(); }

    m.SetTime( 0 );
    m.SetTempo32( 120 * 32 ); // tempo stored as bpm * 32, giving 1/32 bpm resolution

    if( !tracks.GetTrack(0)->PutEvent(m) ) { abort(); }
}